#!/bin/sh

gpioid1=427
SPI_DEV='2803d000.spi'
SPI_PATH='/sys/bus/platform/drivers/phytium_spi'

gpioctrl1=/sys/class/gpio/gpio$gpioid1

echoerr() {
	echo  "ERROR: $@"
}

echoinfo() {
	echo  "$@"
}


if [ ! -e $gpioctrl1 ];then

echo  $gpioid1 >   /sys/class/gpio/export

if [ $? -ne 0 ]; then
 echoerr "gpio427 create is  fail."
 exit 1
fi 

echo out  >  $gpioctrl1/direction
echoinfo  "create  gpio $gpioid1"
fi

#echo "start"  > /var/biosUpProg.log

up_image=$1
IMAGE_FILE=`ls /tmp/images/$up_image/*.fd`

if test "x$up_image" = x
then
  		echoerr "not image."
		exit 1
 
fi 

if test -e "/tmp/images/$up_image"
	then
	   echoinfo "up_image is $up_image"
else
	   echoerr "$up_image not image file."
		exit 1
	
fi


echoinfo bios_update: "$@"


echoinfo "bios_Updating."

#echo "pflash"  > /var/biosUpProg.log

echo  0  > $gpioctrl1/value
if [ $? -ne 0 ]; then 	
 echoerr "$gpioctrl set 0 is  fail."
 exit 1
fi 

#set SPI pin No reuse
#devmem 0x1e6e2070 32 0x020c9456
devmem 0x32b30188 32 0x76

if [[ -d ${SPI_PATH}/$SPI_DEV ]]; then
    echo  "${SPI_DEV}" > ${SPI_PATH}/unbind
fi			            
echo  "${SPI_DEV}" > ${SPI_PATH}/bind

all_mtd_device=`ls /sys/class/mtd/mtd*/name`
for mtd in $all_mtd_device ; do
	d=`cat $mtd`
	if [[ $d == "pnor" ]]; then
		tmp=${mtd%/*}
		BIOS_MTD_DEVICE=/dev/${tmp##*/}
	fi
done

if [ ! -e $BIOS_MTD_DEVICE ]; then
        echoerr "flashcp updated Failed : BIOS mtd device $BIOS_MTD_DEVICE does not exist"
	exit 1
fi
flashcp -v $IMAGE_FILE $BIOS_MTD_DEVICE

#pflash  --direct  -E -f  -p   $up_image   

if [ $? -ne 0 ]; then
 echoerr "$up_image plash fail."
 echo  1  > $gpioctrl1/value
 exit 1
fi

rm /tmp/images/$up_image -rf
usleep 10

#pflash  --direct -3

echo  1  > $gpioctrl1/value

echoinfo "bios image up end" 


#echo "end"  > /var/biosUpProg.log
exit 0

